package com.vcredit.creditcat.web.app;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.IAppTokenManager;
import com.vcredit.creditcat.api.IAuthorizeManager;
import com.vcredit.creditcat.api.ICustAccountManage;
import com.vcredit.creditcat.api.ICustManager;
import com.vcredit.creditcat.api.IMessageManager;
import com.vcredit.creditcat.api.IResourceManger;
import com.vcredit.creditcat.dto.AppLoginInfoDto;
import com.vcredit.creditcat.dto.AppLoginParamDto;
import com.vcredit.creditcat.dto.MessageDto;
import com.vcredit.creditcat.dto.MessageListDto;
import com.vcredit.creditcat.dto.TokenIsValidDto;
import com.vcredit.creditcat.dto.UserRegisterParamDto;
import com.vcredit.creditcat.dto.feedback.FeedBackDto;
import com.vcredit.creditcat.enumtype.AccountTypeEnum;
import com.vcredit.creditcat.enumtype.MessageOperationEnum;
import com.vcredit.creditcat.enumtype.SendSmsTypeEnum;
import com.vcredit.creditcat.exception.CustLoginException;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustAccount;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.creditcat.vo.HeadImgUploadVo;
import com.vcredit.creditcat.vo.JsonResult;
import com.vcredit.creditcat.vo.MessageOperationVo;
import com.vcredit.creditcat.vo.PageQueryParamVo;
import com.vcredit.framework.annotation.Log;

@RestController
@RequestMapping("/user")
public class UserController extends BaseCreditCatController {
	@Reference(version = "1.0")
	private IMessageManager messageManager;
	@Reference(version = "1.0")
	private IAuthorizeManager authorizeManager;
	@Reference(version = "1.0")
	private ICustManager custManager;
	@Reference(version = "1.0", group = "ftp")
	private IResourceManger resourceManger;

	@Reference(version = "1.0")
	private IAppTokenManager appTokenService;
	@Reference(version = "1.0")
	private ICustAccountManage custAccountManage;

	/**
	 * 登录接口
	 * 
	 * @param loginParam
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/login")
	public JsonResult<AppLoginInfoDto> login(@RequestBody @Valid AppLoginParamDto loginParam, HttpServletRequest request) throws Exception {
		AccountTypeEnum accountType = EnumExtUtil.getEnumOnValue(AccountTypeEnum.class, loginParam.getLoginType(), "code");
		if (null == accountType) {
			throw new CustLoginException("登录方式暂不支持");
		}
		switch (accountType) {
		case MobileLogin:
			if (StringUtils.isNotBlank(loginParam.getLoginName()) && StringUtils.isNotBlank(loginParam.getSmsVCode()) && StringUtils.isNotBlank(loginParam.getDeviceId())) {
				if (!(loginParam.getLoginName().matches("^1\\d{10}$") && super.checkVerifyCode(request, loginParam.getLoginName(), loginParam.getSmsVCode(), SendSmsTypeEnum.Login.getCode()))) {
					throw new CustLoginException("手机号码格式错误或验证码已过期");
				}
			} else {
				throw new CustLoginException("登录信息不能为空");
			}
			break;
		case Auto:
			if (StringUtils.isBlank(loginParam.getDeviceId())) {
				throw new CustLoginException("设备号不能为空");
			}
			break;
		case SynchAccount:
			if (StringUtils.isBlank(loginParam.getIdCardNo()) || StringUtils.isBlank(loginParam.getAccessToken())) {
				throw new CustLoginException("账号同步 参数不能为空");
			}
			if (!loginParam.getLoginName().matches("^1\\d{10}$")) {
				throw new CustLoginException("手机号码格式错误");
			}
			break;
		default:
			throw new CustLoginException("登录方式暂不支持");
		}
		AppLoginInfoDto response = authorizeManager.appLogin(loginParam, request.getHeader("appDesc"), request.getHeader("appInfo"));
		super.clearSession(request);
		return JsonResult.SuccessResponse(response);
	}

	/**
	 * 判断token是否有效
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/isitValidTooken")
	public JsonResult<TokenIsValidDto> isitValidTooken(HttpServletRequest request) throws Exception {
		String accessToken = request.getHeader("accessToken");
		Long custId = null;
		CustAccount custAccount = null;
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			custAccount = custAccountManage.findById(custId);
		}
		TokenIsValidDto dto = new TokenIsValidDto();
		dto.setEffectiveToken(appTokenService.tokenIsVaild(custAccount, accessToken));
		return JsonResult.SuccessResponse(dto);
	}

	/**
	 * 获取消息列表
	 * 
	 * @param pageQuery
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/message")
	public JsonResult<MessageListDto> getMessageList(@RequestBody PageQueryParamVo pageQuery, HttpServletRequest request) throws Exception {
		Cust currentCust = getCust(request);

		if (null == pageQuery.getMsgKind() || pageQuery.getMsgKind().toString().trim().length() == 0) {
			pageQuery.setMsgKind(3);
		}

		List<MessageDto> messageList = messageManager.getMessageList(currentCust.getCustId(), pageQuery.getMsgKind(), pageQuery.getPageIndex(), pageQuery.getPageSize());
		return JsonResult.SuccessResponse(new MessageListDto(messageList));
	}

	/**
	 * 设置消息状态（删除/已读）
	 * 
	 * @param opt
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Log
	@RequestMapping(value = "/message/operate")
	public JsonResult setMsgStatus(@RequestBody MessageOperationVo opt, HttpServletRequest request) throws Exception {
		MessageOperationEnum messageOperationEnum = EnumExtUtil.getEnumOnValue(MessageOperationEnum.class, String.valueOf(opt.getOperationKind()), "code");
		if (opt.cMsgIds() != null) {
			messageManager.modifyMessages(opt.cMsgIds(), messageOperationEnum, opt.getMsgKind());
		}
		return JsonResult.SuccessResponse(null);
	}

	/**
	 * 用户注册
	 * 
	 * @param registerParam
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/userRegister")
	public JsonResult<CustAccount> userRegister(@RequestBody @Valid UserRegisterParamDto registerParam, HttpServletRequest request) throws Exception {
		Long accountId = super.getAccountId(request);
		registerParam.setAccountId(accountId);
		Cust cust = super.getCust(request);
		authorizeManager.userRegister(registerParam, cust.getLastProccessId());
		// 清理缓存
		super.clearSession(request);
		return JsonResult.SuccessResponse(null);
	}

	/**
	 * 上传头像
	 * 
	 * @param photoData
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/headImgUpload", method = RequestMethod.POST)
	public JsonResult<CustAccount> headImgUpload(@RequestBody @Valid HeadImgUploadVo photoData, HttpServletRequest request) throws Exception {
		Long accountId = super.getAccountId(request);
		// 上传头像处理
		authorizeManager.headImgUpload(photoData.getPhotoData(), accountId);
		return JsonResult.SuccessResponse(null);
	}

	/**
	 * 获取用户信息
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/getUser")
	public JsonResult<Cust> getUser(HttpServletRequest request) throws Exception {
		Cust cust = super.getCust(request);
		return JsonResult.SuccessResponse(custManager.findById(cust.getCustId()));
	}

	/**
	 * 获取用户信息
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping(value = "/feedback")
	public JsonResult<Object> feedback(@RequestBody @Valid FeedBackDto paramDto, HttpServletRequest request) throws Exception {
		Cust currentCust = super.getCust(request);
		if (null == currentCust) {
			throw new CustLoginException("无用户登录或者未身份认证");
		}
		custManager.saveFeedback(currentCust.getCustId(), paramDto);
		return JsonResult.SuccessResponse(null);
	}
}
